package edu.fiu.cis.personalize.server.berkDB;

import java.util.List;

import com.sleepycat.bind.tuple.TupleBinding;
import com.sleepycat.je.Database;
import com.sleepycat.je.DatabaseEntry;
import com.sleepycat.je.OperationStatus;
import com.sleepycat.je.Transaction;

public class DefaultBtransaction<K, V> implements BTransaction<K, V>
{
	private TupleBinding<K>	keyBinding;
	private TupleBinding<V>	valBinding;

	public DefaultBtransaction(TupleBinding<K> keyBinding,
			TupleBinding<V> valBinding)
	{
		super();
		this.keyBinding = keyBinding;
		this.valBinding = valBinding;
	}

	@Override
	public TupleBinding<K> getKeyBinding() {
		return keyBinding;
	}

	@Override
	public TupleBinding<V> getValueBinding() {
		return valBinding;
	}

	@Override
	public V lookup(Transaction tx, K key, Database database) {
		DatabaseEntry keyEntry = new DatabaseEntry();
		getKeyBinding().objectToEntry(key, keyEntry);
		DatabaseEntry valEntry = new DatabaseEntry();
		OperationStatus status = database.get(null, keyEntry, valEntry, null);
		if (status == OperationStatus.SUCCESS)
			return getValueBinding().entryToObject(valEntry);
		else {
			return null;
		}
	}

	@Override
	public void save(K key, V value, Transaction tx, Database database) {
		DatabaseEntry keyEntry = new DatabaseEntry();
		DatabaseEntry dataEntry = new DatabaseEntry();
		getKeyBinding().objectToEntry(key, keyEntry);
		getValueBinding().objectToEntry(value, dataEntry);
		database.put(tx, keyEntry, dataEntry);
	}

	@Override
	public void save(List<KeyValuePair<K, V>> entries, Transaction tx,
			Database database) {
		for (KeyValuePair<K, V> p : entries) {
			save(p.getKey(), p.getValue(), tx, database);
		}

	}

	@Override
	public boolean remove(K key, Transaction tx, Database database) {
		DatabaseEntry keyEntry = new DatabaseEntry();
		getKeyBinding().objectToEntry(key, keyEntry);
	
		return database.delete(tx, keyEntry) == OperationStatus.SUCCESS;

	}

	

}
